package com.hsd.voice_asr.socket;

import com.hsd.voice_asr.enums.LanguageEnum;
import com.hsd.voice_asr.properties.AliAsrProperties;
import com.hsd.voice_asr.utils.SocketUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

@Slf4j
public class SocketStreamThread extends Thread {

    private Socket socket;

    private AliAsrProperties aliAsrProperties;

    private RealtimeAsr realtimeAsr;

    private String deviceKey = "";

    public SocketStreamThread(Socket socket,AliAsrProperties aliAsrProperties) {
        this.socket = socket;
        this.aliAsrProperties=aliAsrProperties;
    }

    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            initDeviceKdy(inputStream);
            log.info("client socketStreamThread connected {}",deviceKey);
            this.realtimeAsr = new RealtimeAsr(LanguageEnum.CHINESE.getCode(),aliAsrProperties);
            this.realtimeAsr.process(inputStream);
        } catch (Exception e) {
        }finally {
            log.error("client socketStreamThread inputStream close");
            this.realtimeAsr.shutDown();
            SocketUtil.removeSocket(deviceKey);
        }
    }

    private void initDeviceKdy(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[1];
        while (inputStream.read(bytes) > 0) {
            deviceKey += new String(bytes);
            if (deviceKey.indexOf("ACKEND") != -1) {
                deviceKey = deviceKey.substring(10, deviceKey.indexOf("||ACKEND")).trim();
                SocketUtil.addSocket(deviceKey,socket);
                break;
            }
        }
    }

}
